<?php
/**
 * 基于OpenSSL的AES加密
 * @App	
 * @Group 
 * @Action AesOpenssl
 * @author lilei
 * @date 2018年12月29日
 *
 */
namespace app\common\service;
class AesOpenssl {
	
	/**
	 * 需要加密的字符串
	 * @var string
	 */
	var $string;
	
	/**
	 * 密钥
	 * @var string
	 */
	var $key;

    /**
     * AesOpenssl constructor.
     * @param $string
     * @param $key
     * @throws \Exception
     */
	public function __construct( $string, $key ) {
		// 判断是否加载openssl扩展
		if ( !extension_loaded('openssl') ) {
			throw new \Exception('OpenSSL扩展不存在');
		}
		$this->string = $string;
		$this->key = $key;
	}
	
	/**
	 * 加密
	 */
	public function encrypt( ) {
		$data = openssl_encrypt($this->string, 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);
		$data = base64_encode(bin2hex($data));
		return $data;
	}
	
	/**
	 * 解密
	 */
	public function decrypt() {
		$string = base64_decode($this->string);
		$decrypted = openssl_decrypt(hex2bin($string), 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);
		
		return $decrypted;
	}
}